package com.lenovo.testreport.online.web.smoke.service;

import com.lenovo.testreport.online.web.smoke.mapper.OnlineWebSmokeCaseMapper;
import com.lenovo.testreport.online.web.smoke.model.OnlineWebSmokeCase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author CJF
 * @date 2018/10
 * @version Updated at 2019/05/24 By Howie Lu
 */
@Service("OnlineWebSmokeCaseService")
public class OnlineWebSmokeCaseServiceImpl implements OnlineWebSmokeCaseService {
    @Autowired
    private OnlineWebSmokeCaseMapper mapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    synchronized public List<OnlineWebSmokeCase> findByRid(String tablename, int rid) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        String key = tablename + "/rid/" + rid;
        redisTemplate.setKeySerializer(redisSerializer);
        List<OnlineWebSmokeCase> List = (List<OnlineWebSmokeCase>) redisTemplate.opsForValue().get(key);
        if (List == null) {
            List = mapper.selectByRid(tablename, rid);
            redisTemplate.opsForValue().set(key, List, 120, TimeUnit.SECONDS);
        }
        return List;
    }

    @Override
    synchronized public List<OnlineWebSmokeCase> findByCid(String tablename, int cid) {

        RedisSerializer redisSerializer = new StringRedisSerializer();
        String key = tablename + "/cid/" + cid;
        redisTemplate.setKeySerializer(redisSerializer);
        List<OnlineWebSmokeCase> List = (List<OnlineWebSmokeCase>) redisTemplate.opsForValue().get(key);
        if (List == null) {
            List = mapper.selectByCid(tablename, cid);
            redisTemplate.opsForValue().set(key, List, 120, TimeUnit.SECONDS);
            // System.out.println(key + " 缓存中没找到，访问数据库！");
        } //else System.out.println(key + " 缓存中找到了，无需访问数据库！");
        return List;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    synchronized public int addCase(String tablename, OnlineWebSmokeCase cases) {

        return mapper.insert(tablename, cases);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    synchronized public int modifycase(String tablename, OnlineWebSmokeCase online_websmoke_case) {
        int result = mapper.updateTrackByCid(tablename, online_websmoke_case);

        String key = tablename + "/cid/" + online_websmoke_case.getCid();
        redisTemplate.delete(key);
        return result;
    }
}
